package com.ambitor.ipro.app.sche;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.BlockingQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ambitor.grass.sql.dao.SuperDao;
import com.ambitor.grass.sql.dao.impl.SuperDaoImpl;
import com.ambitor.grass.util.data.IData;
import com.ambitor.grass.util.data.IDataset;
import com.ambitor.ipro.util.Constants;
import com.ambitor.ipro.util.LocalConnectionUtils;
import com.ambitor.ipro.util.StringUtil;

public class TaskCarrier implements Runnable {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	private BlockingQueue<IData> taskQueue = null;
	private SuperDao superDao = null;

	public TaskCarrier(BlockingQueue<IData> taskQueue) {
		this.taskQueue = taskQueue;
	}

	@Override
	public void run() {
		while (true) {
			execute();
		}
	}

	private void execute() {
		Connection conn = null;
		try {
			conn = getConnection();
			superDao = new SuperDaoImpl(conn);
			IDataset taskList = scannTask();
			if (taskList.size() == 0) {
				logger.info("取出满足条件的工单0条，将休息一会...");
				sleep(Constants.SCANN_PRO_INTERVAL);
				return;
			}
			logger.info("取出满足条件的工单" + taskList.size() + "条，马上开始执行...");
			StringBuilder batchIds = new StringBuilder();
			for (int i = 0; i < taskList.size(); i++) {
				IData task = taskList.getData(i);
				taskQueue.offer(task);
				batchIds.append(task.getString("BATCH_ID"));
				batchIds.append(",");
			}
			String batchIdsStr = StringUtil
					.trimSuffix(batchIds.toString(), ",");
			String sql = "update tf_p_trade_pro_batch set trade_state = 'Q' " +
					"where batch_id in("
					+ batchIdsStr + ")";
			superDao.getBaseDao().executeUpdate(sql);
		} catch (Exception e) {
			logger.error("任务调度器新增任务过程中发生异常", e);
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				logger.warn("conn.close()出现异常", e);
			}
		}
	}

	/**
	 * 获取未执行的任务
	 * 
	 * @return
	 * @throws Exception
	 */
	private IDataset scannTask() throws Exception {
		IDataset tradeProBatchList = superDao.executeBaseOnSqlSql(
				"TF_P_TRADE_PRO_BATCH", "SELECT_TASK_TO_EXEC_ALL");
		return tradeProBatchList;
	}

	private Connection getConnection() {
		Connection conn = null;
		int tryTimes = 0;
		while (tryTimes < Constants.TAOBAO_API_CALL_MAX_TIMES) {
			try {
				conn = LocalConnectionUtils.getConnection();
				break;
			} catch (SQLException e) {
				logger.error("获取Connection出现异常");
				tryTimes++;
				sleep(500);
			}
		}
		return conn;
	}

	private void sleep(int time) {
		try {
			Thread.sleep(time);
		} catch (InterruptedException exp) {
		}
	}
}
